package com.lx.oms.controller.baidu.ueditor.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lx.oms.common.utils.ImageOperation;
import com.lx.oms.controller.baidu.ueditor.define.AppInfo;
import com.lx.oms.controller.baidu.ueditor.define.BaseState;
import com.lx.oms.controller.baidu.ueditor.define.FileType;
import com.lx.oms.controller.baidu.ueditor.define.State;

public class RchBinaryUploader {

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}
		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
		if (isAjaxUpload) {
			upload.setHeaderEncoding("UTF-8");
		}
		try {
			FileItemIterator iterator = upload.getItemIterator(request);
			while (iterator.hasNext()) {
				fileStream = iterator.next();
				if (!fileStream.isFormField()) {
					break;
				}
				fileStream = null;
			}
			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}
			
			String originFileName = fileStream.getName();
			String suffix = FileType.getSuffixByFilename(originFileName);
			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			
			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}
			Random random = new Random();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < 3; i++) {
				buffer.append(random.nextInt(9));
			}
			
			//图片重命名写入
			String targetFileName = (new Date()).getTime() + buffer.toString() + suffix;
			
			long maxSize = ((Long) conf.get("maxSize")).longValue();
			// 上传文件到服务器
			InputStream inputStream = fileStream.openStream();
			String pathUrl = request.getSession().getServletContext().getRealPath("/")+("/fileImage/");
			
			State storageState = StorageManager.saveFileByInputStream(inputStream,pathUrl+targetFileName, maxSize);
			
			String url = ImageOperation.encodeImage(targetFileName,pathUrl);
			
			inputStream.close();
			if (storageState.isSuccess()) {
				storageState.putInfo( "size", "");
				storageState.putInfo( "title", targetFileName);
				storageState.putInfo("url", url);
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}
			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		} catch (Exception e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} finally {
		}
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);
		return list.contains(type);
	}
}
